package com.kaka.uploader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.kaka.util.DateUtil;
import com.kaka.util.SystemUtil;


@RestController
public class UploadController {

	@Value("${application.path.win}")
	private String winPath = null;
	@Value("${application.path.linux}")
	private String linuxPath = null;

	@RequestMapping({"/test"})
	@ResponseBody
	public String welcome(Map<String, Object> model)
	{
		model.put("time", new Date());
		model.put("message", "hello boot");
		return "welcome";
	}

	@RequestMapping({"/crmupload"})
	public String crmupload(@RequestParam("file") MultipartFile file, HttpServletRequest request)
			throws IOException
	{
		String name = file.getOriginalFilename();
		if ((StringUtils.isBlank(name)) || (!name.contains("."))) {
			return "";
		}
		String path;
		if (SystemUtil.isWin()) {
			path = this.winPath;
		} else {
			path = this.linuxPath;
		}
		path = path + "img";
		String type = "crm";
		if (!file.isEmpty()) {
			try
			{
				String yyyymmdd = DateUtil.getDate();
				String folder = yyyymmdd.substring(0, 4) + "/" + yyyymmdd.substring(4, 6) + "/" + yyyymmdd.substring(6, 8);

				File f = new File(path + File.separator + type + File.separator + folder);
				if (!f.exists()) {
					f.mkdirs();
				}
				String extendtion = name.substring(name.lastIndexOf(".") + 1);
				String uuid = UUID.randomUUID().toString();
				name = uuid + "." + extendtion;
				String filePath = path + File.separator + type + File.separator + folder + File.separator + name;

				File dest = new File(filePath);
				FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));

				return "/img/" + type + "/" + folder + "/" + name;
			}
			catch (Exception e)
			{
				e.printStackTrace();
				return "";
			}
		}
		return "";
	}

	@RequestMapping({"/upload"})
	public Object upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, String type)
			throws IOException
	{
		Map<String, String> map = new HashMap();
		if (StringUtils.isBlank(type))
		{
			map.put("status", "1");
			map.put("path", "");
			map.put("err", "type不能为空");
			return map;
		}
		String name = file.getOriginalFilename();
		if ((StringUtils.isBlank(name)) || (!name.contains(".")))
		{
			map.put("status", "1");
			map.put("path", "");
			map.put("err", "无效的文件名或类型");
			return map;
		}
		String path;
		if (SystemUtil.isWin()) {
			path = this.winPath;
		} else {
			path = this.linuxPath;
		}
        path = path + "img";
		if (!file.isEmpty()) {
			try
			{
				String yyyymmdd = DateUtil.getDate();
				String folder = yyyymmdd.substring(0, 4) + "/" + yyyymmdd.substring(4, 6) + "/" + yyyymmdd.substring(6, 8);

				File f = new File(path + File.separator + type + File.separator + folder);
				if (!f.exists()) {
					f.mkdirs();
				}
				String extendtion = name.substring(name.lastIndexOf(".") + 1);
				String uuid = UUID.randomUUID().toString();
				name = uuid + "." + extendtion;
				String filePath = path + File.separator + type + File.separator + folder + File.separator + name;

				File dest = new File(filePath);
				FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));

				map.put("status", "0");
				map.put("path", "/img/" + type + "/" + folder + "/" + name);
			}
			catch (Exception e)
			{
				e.printStackTrace();
				map.put("status", "1");
				map.put("path", "");
			}
		}
		return map;
	}

	/**
	 * {
	 "code": 0 //0表示成功，其它表示失败
	 ,"msg": "" //失败信息
	 ,"data": {
	 "src": "http://cdn.xxx.com/upload/images/a.jpg" //图片url
	 }
	 }
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
//	@RequestMapping("/chatUploadImg")
//	public Object chatUploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
//		String type = "chat";
//		Map<String, Object> map = new HashMap<String, Object>();
//		if(StringUtils.isBlank(type)) {
//			map.put("code", "1");
//			map.put("data", null);
//			map.put("msg", "type不能为空");
//			return map;
//		}
//		String name = file.getOriginalFilename();
//		String path;
//		if(SystemUtil.isWin()) {
//			path = this.winPath;
//		} else {
//			path = this.linuxPath;
//		}
//		if (!file.isEmpty()) {
//			try {
//				String folder = DateUtil.getDate();
//				{
//					File f = new File(path + File.separator + type + File.separator + folder);
//					if(!f.exists()) {
//						f.mkdirs();
//					}
//				}
//				String filePath = path + File.separator + type + File.separator + folder + File.separator + name;
//				//生成目标文件
//				File dest = new File(filePath);
//				FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));
//
//				String url = "http://image.1872.net/img/"+ type + "/" + folder + "/" + name;
//				map.put("code", "0");
//				Map<String, String> dataMap = new HashMap<>();
//				dataMap.put("src", url);
//				map.put("data", dataMap);
//				map.put("msg", "");
//			} catch (Exception e) {
//				e.printStackTrace();
//				map.put("code", "1");
//				map.put("data", null);
//				map.put("msg", "type不能为空");
//				return map;
//			}
//		}
//		return map;
//	}


    @RequestMapping({"/chatUploadImg"})
    public Object chatUploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IOException
    {
        Map<String, Object> map = new HashMap<>();
        String type = "chat";
        String name = file.getOriginalFilename();
        if ((StringUtils.isBlank(name)) || (!name.contains("."))) {
            return "";
        }
        String path;
        if (SystemUtil.isWin()) {
            path = this.winPath;
        } else {
            path = this.linuxPath;
        }
        path = path + "img";
        if (!file.isEmpty()) {
            try
            {
                String yyyymmdd = DateUtil.getDate();
                String folder = yyyymmdd.substring(0, 4) + "/" + yyyymmdd.substring(4, 6) + "/" + yyyymmdd.substring(6, 8);

                File f = new File(path + File.separator + type + File.separator + folder);
                if (!f.exists()) {
                    f.mkdirs();
                }
                String extendtion = name.substring(name.lastIndexOf(".") + 1);
                String uuid = UUID.randomUUID().toString();
                name = uuid + "." + extendtion;
                String filePath = path + File.separator + type + File.separator + folder + File.separator + name;

                File dest = new File(filePath);
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));

                String url = "http://image.1872.net/img/"+ type + "/" + folder + "/" + name;
				map.put("code", "0");
				Map<String, String> dataMap = new HashMap<>();
				dataMap.put("src", url);
				map.put("data", dataMap);
				map.put("msg", "");
            }
            catch (Exception e)
            {
                e.printStackTrace();
				map.put("code", "1");
				map.put("data", null);
				map.put("msg", "type不能为空");
				return map;
            }
        }
        return map;
    }

    /**
     * {
     "code": 0 //0表示成功，其它表示失败
     ,"msg": "" //失败信息
     ,"data": {
     "src": "http://cdn.xxx.com/upload/file/LayIM.zip" //文件url
     ,"name": "LayIM.zip" //文件名
     }
     }
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping({"/chatUploadFile"})
    public Object chatUploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request)
            throws IOException
    {
        Map<String, Object> map = new HashMap<>();
        String type = "chat";
        String name = file.getOriginalFilename();
        if ((StringUtils.isBlank(name)) || (!name.contains("."))) {
            return "";
        }
        String path;
        if (SystemUtil.isWin()) {
            path = this.winPath;
        } else {
            path = this.linuxPath;
        }
        path = path + "file";
        if (!file.isEmpty()) {
            try
            {
                String yyyymmdd = DateUtil.getDate();
                String uuid = UUID.randomUUID().toString();
                String folder = yyyymmdd.substring(0, 4) + "/" + yyyymmdd.substring(4, 6) + "/" + yyyymmdd.substring(6, 8);
                String fileName = name;
                if(fileName.contains(".")){
                    fileName = fileName.substring(0, name.lastIndexOf(".") );
                }
                folder = folder + "/" + fileName + uuid;

                File f = new File(path + File.separator + type + File.separator + folder);
                if (!f.exists()) {
                    f.mkdirs();
                }
//                String extendtion = name.substring(name.lastIndexOf(".") + 1);
//                name = uuid + "." + extendtion;
                String filePath = path + File.separator + type + File.separator + folder + File.separator + name;

                File dest = new File(filePath);
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));

                String url = "http://image.1872.net/file/"+ type + "/" + folder + "/" + name;
                map.put("code", "0");
                Map<String, String> dataMap = new HashMap<>();
                dataMap.put("src", url);
                dataMap.put("name",  file.getOriginalFilename());
                map.put("data", dataMap);
                map.put("msg", "");
            }
            catch (Exception e)
            {
                e.printStackTrace();
                map.put("code", "1");
                map.put("data", null);
                map.put("msg", "type不能为空");
                return map;
            }
        }
        return map;
    }
}
